#include <QtGui>

#include "renderarea.h"
#include "window.h"
using namespace std;
//! [0]
const int IdRole = Qt::UserRole;
//! [0]
void delay(int msec)
{
  QTime dieTime= QTime::currentTime().addMSecs(msec);
  while( QTime::currentTime() < dieTime )
    QCoreApplication::processEvents(QEventLoop::AllEvents, 100);    
}
//! [1]
Window::Window()
{
  anim=0;
  Jungle=new ether;
  connect(Jungle,SIGNAL(timeChanged(double)),this,SLOT(setRobots()));
  Jungle->setlogOff();

  
  
  int frameStyle = QFrame::Sunken | QFrame::StyledPanel;
  simulatePushButton=new QPushButton;
  simulatePushButton->setText("Step");
  connect(simulatePushButton, SIGNAL(clicked()),
	  this, SLOT(simulate()));
  
  animatePushButton=new QPushButton;
  animatePushButton->setText("Animate");
  connect(animatePushButton, SIGNAL(clicked()),
	  this, SLOT(animate()));
  
  resetPushButton=new QPushButton;
  resetPushButton->setText("Reset");
  connect(resetPushButton, SIGNAL(clicked()),
	  this, SLOT(reloadData()));
  
  creditsPushButton=new QPushButton;
  creditsPushButton->setText("Credits");
  connect(creditsPushButton, SIGNAL(clicked()),
	  this, SLOT(credits()));
  
  deltaTimeSpinBox = new QDoubleSpinBox;
  deltaTimeSpinBox->setMinimum(Jungle->returnStepTime());
  deltaTimeSpinBox->setSingleStep(Jungle->returnStepTime());
  deltaTimeLabel = new QLabel(tr("StepTime:"));
  deltaTimeLabel->setBuddy(deltaTimeSpinBox);
  
  speedTimeSlider= new QSlider;
  speedTimeSlider->setOrientation(Qt::Horizontal);
  speedTimeSlider->setRange(100,300);
  speedTimeSlider->setSliderPosition(200); 
  speedTimeLabel=new QLabel(tr("BulletTime:"));
  
  currentTimeLabel = new QLabel;
  currentTimeLabel->setFrameStyle(frameStyle);
  currentTimeLabel->setText(tr("Time=")+QString::number(Jungle->timereturn()));
  
  openFileMapLabel = new QLabel;
  openFileMapLabel->setFrameStyle(frameStyle);
  openFileMapButton =  new QPushButton(tr("Open Map"));
  connect(openFileMapButton, SIGNAL(clicked()),
	  this, SLOT(setOpenFileMap()));
  openFileRobotsLabel = new QLabel;
  openFileRobotsLabel->setFrameStyle(frameStyle);
  openFileRobotsButton =  new QPushButton(tr("Open Robots"));
  connect(openFileRobotsButton, SIGNAL(clicked()),
	  this, SLOT(setOpenFileRobots()));

  
  selectLogLabel = new QLabel;
  selectLogLabel->setFrameStyle(frameStyle);
  selectLogButton= new QPushButton(tr("Select Log"));
  connect(selectLogButton, SIGNAL(clicked()),
	  this, SLOT(setLogFile()));
  logCheckBox=new QCheckBox;
  logCheckBox->setChecked(false);
  logCheckBox->setEnabled(false);
  connect(logCheckBox, SIGNAL(stateChanged (int)),
	  this, SLOT(checkLog()));
  
  connect(this, SIGNAL(destroyed()),
	  this, SLOT(animate()));
  
  
  renderArea = new RenderArea;
  QDir pwd; 
  openFileMapLabel->setText(pwd.filePath("maps/default.pbm"));
  openFileRobotsLabel->setText(pwd.filePath("agents/default.dat"));
  
  
  Table = new QTableWidget(0,4);
  QStringList labels;
  labels <<tr("Robot\nPriority") <<tr("Position") << tr("Reserved\nPosition")<<tr("State");
  Table->setHorizontalHeaderLabels(labels);
  Table->horizontalHeader()->setResizeMode( QHeaderView::Fixed);
  Table->horizontalHeader()->resizeSection(0,50);
  Table->horizontalHeader()->resizeSection(1,60);
  Table->horizontalHeader()->resizeSection(2,60);
  Table->horizontalHeader()->resizeSection(3,80);
  Table->horizontalHeader()->setStretchLastSection(true);
  Table->setShowGrid(true);
  Table->setEditTriggers(QAbstractItemView::NoEditTriggers);//readonly
  Table->verticalHeader()->setVisible(false);
  
  reloadData();
  

  QGridLayout *mainLayout = new QGridLayout;

  
  mainLayout->setRowStretch(0, 1);
  mainLayout->setRowMinimumHeight(0, 200);
  mainLayout->setColumnStretch(1, 1);
  mainLayout->setColumnStretch(6, 1);  
  mainLayout->setColumnMinimumWidth(1, 100);
  mainLayout->setColumnMinimumWidth(6, 100);
  mainLayout->setColumnMinimumWidth(7, Table->sizeHint().rwidth());
  mainLayout->addWidget(renderArea, 0, 0, 1, 7);
  mainLayout->addWidget(openFileMapButton, 1, 0);
  mainLayout->addWidget(openFileMapLabel, 1, 1,1,2);
  mainLayout->addWidget(openFileRobotsButton, 2, 0);
  mainLayout->addWidget(openFileRobotsLabel, 2,1,1,2);
  mainLayout->addWidget(selectLogButton, 3, 0);
  mainLayout->addWidget(selectLogLabel, 3,1);
  mainLayout->addWidget(logCheckBox, 3,2);
  mainLayout->addWidget(animatePushButton, 1, 3);
  mainLayout->addWidget(speedTimeLabel, 1, 4, Qt::AlignLeft);
  mainLayout->addWidget(speedTimeSlider, 1, 5,1,2);
  mainLayout->addWidget(simulatePushButton, 2, 3);
  mainLayout->addWidget(deltaTimeLabel, 2, 4, Qt::AlignLeft);
  mainLayout->addWidget(deltaTimeSpinBox, 2, 5);
  mainLayout->addWidget(currentTimeLabel,2,6);
  mainLayout->addWidget(resetPushButton, 3, 3);
  mainLayout->addWidget(creditsPushButton, 3, 4,1,2);
  mainLayout->addWidget(Table, 0, 7, 4, 1);  

  


  setLayout(mainLayout);  
  setWindowTitle(tr("AnnoyingAnacodnas"));
}
Window::~Window(){
  if(FileLog.good()) {
    FileLog.close();
  }
}

void Window::simulate()
{

  Jungle->runSimulation(Jungle->timereturn()+deltaTimeSpinBox->value());
  currentTimeLabel->setText(tr("Time=")+QString::number(Jungle->timereturn()));

}

void Window::animate()
{
  if(anim==0){
    animatePushButton->setText("Stop");
    anim=1;
  }
  else{
    animatePushButton->setText("Animate");
    anim=0;
  }
  while(anim){
    delay((int)pow(10.0,0.01*(double)speedTimeSlider->value()));
    Jungle->runSimulation(Jungle->timereturn()+Jungle->returnStepTime());
    currentTimeLabel->setText(tr("Time=")+QString::number(Jungle->timereturn()));
  }
  
}
void Window::setRobots()
{
  
  renderArea->setRobots(Jungle->returnRobots());
  updateTable();
}
void Window::setOpenFileMap()
{
  QFileDialog::Options options;
  QString selectedFilter;
  QString fileName = QFileDialog::getOpenFileName(this,
						  tr("Open Map"),
						  openFileMapLabel->text(),
						  tr("All Usable Files (*.pbm *.pgm *.ppm);;*.pbm Files (*.pbm);;*.pgm Files (*.pgm);;*.ppm Files (*.ppm);;All Files (*)"),
						  &selectedFilter,
						  options);
  if (!fileName.isEmpty()){
    openFileMapLabel->setText(fileName);
    openFileRobotsLabel->clear();
    reloadData();
  }
}

void Window::setOpenFileRobots()
{
  QFileDialog::Options options;
  QString selectedFilter;
  QString fileName = QFileDialog::getOpenFileName(this,
						  tr("Open Robots"),
						  openFileRobotsLabel->text(),
						  tr("*.dat Files (*.dat);;All Files (*)"),
						  &selectedFilter,
						  options);
  if (!fileName.isEmpty()){
    openFileRobotsLabel->setText(fileName);
    reloadData();
  }
}

void Window::setLogFile()
{
  QFileDialog::Options options;
  QString selectedFilter;
  QString fileName = QFileDialog::getSaveFileName(this,
						  tr("Select Log"),
						  openFileRobotsLabel->text(),
						  tr("*.log Files (*.log);;All Files (*)"),
						  &selectedFilter,
						  options);
  if (!fileName.isEmpty()){
    selectLogLabel->setText(fileName);
    FileLog.open ("log", fstream::in | fstream::out | fstream::app );
    if(FileLog.good()) {
      cout <<"Opening log ";
      Jungle->loadLog( FileLog );
    }
    else cerr << "No file !"<<endl;
  }
  logCheckBox->setEnabled(true);
  logCheckBox->setChecked(true);
}

void Window::reloadData(){
  QByteArray temp=openFileMapLabel->text().toLocal8Bit();  
  FileMap.open (temp.data(), fstream::in );
  if(FileMap.good()) {
    cout <<"Opening file "<<temp.data()<<endl;
    ether* oldJungle=Jungle;
    Jungle->resetPriority();
    Jungle=new ether;
    if(oldJungle){
      cout<<"delete"<<endl;
      delete oldJungle;}
      
    Jungle->loadMap( FileMap );  
    cout<<"trala"<<endl;
    connect(Jungle,SIGNAL(timeChanged(double)),this,SLOT(setRobots()));
    
    FileMap.close();

    renderArea->setMap(Jungle->returnMapSize(),Jungle->returnMap());

  }
  else cerr << "No file !"<<endl;
  temp=openFileRobotsLabel->text().toLocal8Bit();
  FileRobots.open (temp.data(), fstream::in );
  if(FileRobots.good()) {
    cout <<"Loading robots file "<<temp.data();
    Jungle->loadRobots( FileRobots );
    FileRobots.close();
  }
  else cerr << "No file !"<<endl;
  
  Jungle->setTime(0.0);
  currentTimeLabel->setText(tr("Time=")+QString::number(Jungle->timereturn()));
}
  


void Window::updateTable(){
  //cerr<<"state"<<endl;
  
  this->Robots=Jungle->returnRobots();
  Table->clear();
  Table->setRowCount(0);
  QStringList labels;
  labels <<tr("Robot\nPriority") <<tr("Position") << tr("Reserved\nPosition")<<tr("State");
  Table->setHorizontalHeaderLabels(labels);
  Table->horizontalHeader()->setResizeMode(QHeaderView::Fixed);
  Table->horizontalHeader()->resizeSection(0,50);
  Table->horizontalHeader()->resizeSection(1,60);
  Table->horizontalHeader()->resizeSection(2,60);
  Table->horizontalHeader()->resizeSection(3,80);
  Table->horizontalHeader()->setStretchLastSection(true);
  QTableWidgetItem *item;
  list<robot*>::iterator it = Robots.begin();
  int i=0;
  while(it != Robots.end()){
    Table->insertRow(i);
    item=new QTableWidgetItem(QString("R")+QString::number((*it)->getPriority()));
    Table->setItem(i,0,item);
    item=new QTableWidgetItem(tr("(")+QString::number(imag((*it)->getState().getPosition()))+tr(", ")+QString::number(real((*it)->getState().getPosition()))+tr(")"));
    Table->setItem(i,1,item);
    item=new QTableWidgetItem(tr("(")+QString::number(imag((*it)->getState().getReservedPosition()))+tr(", ")+QString::number(real((*it)->getState().getReservedPosition()))+tr(")"));
    Table->setItem(i,2,item);
    item=new QTableWidgetItem((*it)->getState().QGetLoadState());
    Table->setItem(i,3,item);
    ++it;++i;
  }
  Table->sortItems(0);
}

void Window::checkLog(){
  if(logCheckBox->checkState())
    Jungle->setlogOn();
  else
    Jungle->setlogOff();
}

void Window::closeEvent(QCloseEvent * event){
  anim=0;
  event->accept(); 
}

void Window::credits(){
  /*
  QMessageBox _credits( tr("Credits"),
  "Autorzy:\nDagna Bieda\nNatalia Czop\nMichał Dziergwa\nMaciej Gawron\nPaweł Kułakowski\nMariusz Orda\nKrzysztof Szydłowski",
  QMessageBox::Information,
  QMessageBox::Yes | QMessageBox::Default,
  QMessageBox::No);
  _credits.setButtonText( QMessageBox::Yes, "Ok" );
  _credits.setButtonText( QMessageBox::No, "Wumpus?" );
  switch( _credits.exec() ) {
    case QMessageBox::Yes:
      break;
    case QMessageBox::No:
      currentTimeLabel->setText(tr("WUMPUS ŚMIERDZI JAK MARIUSZ ORDA!"));
      break;

  }*/
  QMessageBox msgBox;
  msgBox.setText("Autorzy:\nDagna Bieda\nNatalia Czop\nMichal Dziergwa\nMaciej Gawron\nPawel Kulakowski\nMariusz Orda\nKrzysztof Szydlowski");
  QAbstractButton* pButtonNo =msgBox.addButton(tr("OK"), QMessageBox::NoRole);
  QAbstractButton* pButtonYes=msgBox.addButton(tr("Wumpus?"), QMessageBox::YesRole);


  
  
  msgBox.exec();
  if(msgBox.clickedButton() == pButtonYes)
  {
    currentTimeLabel->setText(tr("WUMPUS SMIERDZI JAK MARIUSZ ORDA!"));
  }

  
}
  

